package com.shanghaionstar.carmanage.pay.alipay;

import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.Base64;
import com.onstar.cn.more.entity.PackageInfo;
import com.onstar.cn.payme.entity.PaymentInfoEntity;
import com.onstar.cn.payme.payutil.wxpay.PayUtil;

import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
* @ClassName: AliPayCheckUtil
* @Description: AliPayCheckUtil
* @author Xiaofeng Feng
* @date 2015年9月9日 下午2:01:28
 */
public class AliPayCheckUtil {
	private static final LogManager logger = LogManager.getInstance(); // 记录日志
	private static final String ALGORITHM = "RSA";
	private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
	private static final String DEFAULT_CHARSET = "UTF-8";

	/**
	 *
	* @Title: checkAlipay
	* @param @param paymentInfo
	* @param @param packageInfo
	* @param @param orderId
	* @param @param alipayType
	* @param @param accountNo
	* @param @param resultHandler    设定文件
	* @return void    返回类型
	* @throws
	 */
	public void checkAlipay(final PaymentInfoEntity paymentInfo, final PackageInfo packageInfo, final String orderId,
								   final String alipayType, final String accountNo) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String url = "https://mapi.alipay.com/gateway.do?";
				String params = "_input_charset=utf-8";
				params += "&buyer_account_no=" + accountNo;
				params += "&buyer_reg_date=2014-04-10";
				params += "&order_amount="+ packageInfo.getActualPrice();
				params += "&order_category=VehicleService";
				params += "&order_credate_time=" + sdf.format(new Date());
				params += "&order_item_name=" + packageInfo.getPackageName();
				params += "&order_no=" + orderId;
				params += "&partner=" + paymentInfo.getAlipayPartnerID();
				params += "&scene_code=PAYMENT";
				params += "&seller_account_no=" + paymentInfo.getAlipaySeller();
				params += "&seller_reg_date=2014-04-10";
				params += "&service=alipay.security.risk.detect";
				params += "&terminal_type=" + alipayType;
				params += "&timestamp=" + System.currentTimeMillis();
				String sign = sign(params, paymentInfo.getAlipayPrivateKey());
				try {
					sign = URLEncoder.encode(sign, "utf-8");
				} catch (Exception e) {
					e.printStackTrace();
				}
				params += "&sign_type=RSA&sign=" + sign;
				checkListener.onCheckSuccess();
				try {
                    String result="";
                    byte[] byteResult = PayUtil.httpGetRequest(url + params);
                    if(byteResult != null) {
                        result = new String(byteResult);
                    }
					checkListener.onCheckFail(result);
					logger.d("Alipay check:"+result);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	/**
	 *
	* @Title: checkAlipay
	* @param @param paymentInfo
	* @param @param packageInfo
	* @param @param orderId
	* @param @param alipayType
	* @param @param accountNo
	* @param @param resultHandler    设定文件
	* @return void    返回类型
	* @throws
	 */
	public void checkAlipay(final String params) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String url = "https://mapi.alipay.com/gateway.do?";
				checkListener.onCheckSuccess();
				try {
                    String result="";
                    byte[] byteResult = PayUtil.httpGetRequest(url + params);
                    if(byteResult != null) {
                        result = new String(byteResult);
                    }
					checkListener.onCheckFail(result);
					logger.d("Alipay check:"+result);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	/**
	 *
	* @Title: sign
	* @param @param content
	* @param @param privateKey
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String sign(String content, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
					Base64.decode(privateKey));
			KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);

			java.security.Signature signature = java.security.Signature
					.getInstance(SIGN_ALGORITHMS);

			signature.initSign(priKey);
			signature.update(content.getBytes(DEFAULT_CHARSET));

			byte[] signed = signature.sign();

			return Base64.encode(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	AliCheckListener checkListener;

	public void setCheckListener(AliCheckListener checkListener) {
		this.checkListener = checkListener;
	}

	public interface AliCheckListener{
		void onCheckSuccess();

		void onCheckFail(String result);
	}
}
